import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/auth/LoginView.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/auth/RegisterView.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      component: () => import('@/layouts/DefaultLayout.vue'),
      children: [
        {
          path: '',
          name: 'home',
          component: () => import('@/views/HomeView.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'animals',
          name: 'animals',
          component: () => import('@/views/animals/AnimalList.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'animals/:id',
          name: 'animal-detail',
          component: () => import('@/views/animals/AnimalDetail.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'map',
          name: 'map',
          component: () => import('@/views/MapView.vue'),
          meta: { requiresAuth: true }
        },
        {
          path: 'tickets',
          name: 'tickets',
          component: () => import('@/views/TicketView.vue'),
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  if (to.meta.requiresAuth && !userStore.token) {
    next('/login')
  } else {
    next()
  }
})

export default router
